<template>
  <div class="activities-shop">
    <!-- 筛选头部 -->
    <div class="search-box">
      <el-form ref="activitySearchForm" :inline="true" :model="activitySearchInfo" class="search-form">
        <el-form-item label="活动名称：">
          <el-input v-model="activitySearchInfo.name" size="medium" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动状态：">
          <el-select v-model="activitySearchInfo.type" size="medium" placeholder="请输入活动状态">
            <el-option label="已开始" value="1" />
            <el-option label="已结束" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="起止日期：">
          <el-col>
            <el-date-picker
              v-model="activitySearchInfo.date"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="medium"
              placeholder="请选择起止日期"
            />
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="medium" @click="toSearch">查询</el-button>
          <el-button size="medium" @click="resetSearchInfo">重 置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 活动列表 -->
    <div class="ad-list-wrapper">
      <div v-loading="loading" class="ad-list">
        <div class="ad-list-func">
          <div>
            <el-checkbox v-model="checkedAll" @change="checkAll">全部</el-checkbox>
            <el-button class="button" icon="el-icon-delete" size="small" @click="deleteMany">批量删除</el-button>
            <p class="selected-num">已选择 <span>{{ checkedCount }}</span> 项</p>
            <el-button type="text" @click="clearAll">清空</el-button>
          </div>
          <router-link :to="{name: 'ShopActivityAdd'}"><el-button type="primary" icon="el-icon-plus" size="small">添加活动</el-button></router-link>
        </div>
        <div v-if="activities.length === 0" class="none">
          你还没有添加活动～
        </div>
        <table v-else width="100%" align="left" border="0" cellpadding="0" cellspacing="0">
          <thead>
            <tr><th class="checkbox" /><th class="img">活动图片</th><th>活动名称</th><th class="type">活动类型</th><th class="state">活动截止时间</th><th>创建时间</th><th class="func">操作</th></tr>
          </thead>
          <tbody>
            <tr v-for="(ac, index) in activities" :key="index" class="ad-list-item">
              <td class="check"><el-checkbox v-model="ac.selected" @change="checkItem" /></td>
              <td><el-image style="width: 300px; height: 100px" :src="qnPath(ac.imageWeb)" fit="fit" /></td>
              <td>{{ ac.name }}</td>
              <td v-if="ac.type === '02200001'">折扣-{{ ac.disCount }}折</td>
              <td v-if="ac.type === '02200002'">满减-满{{ ac.disCount }}减{{ ac.disCount }}</td>
              <td class="date">
                <p>{{ new Date(ac.beginTime) | getDate }}至{{ new Date(ac.finishTime) | getDate }}</p>
                <p v-if="ac.finishTime - parseInt(new Date().getTime()) > 0" class="times">
                  <template v-if="parseInt(new Date().getTime()) - ac.beginTime > 0">
                    <span>{{ (ac.finishTime - parseInt(new Date().getTime())) | formatDays }}</span>天
                    <span>{{ (ac.finishTime - parseInt(new Date().getTime())) | formatHours }}</span>时
                    <span>{{ (ac.finishTime - parseInt(new Date().getTime())) | formatMins }}</span>分
                  </template>
                  <template v-else>
                    <span>{{ (ac.finishTime - ac.beginTime) | formatDays }}</span>天
                    <span>{{ (ac.finishTime - ac.beginTime) | formatHours }}</span>时
                    <span>{{ (ac.finishTime - ac.beginTime) | formatMins }}</span>分
                  </template>
                </p>
                <p v-else style="font-size: 14px; color:#f75757;margin-top: 10px;">活动过期</p>
              </td>
              <td class="create-date">{{ new Date(ac.createTime) | getDate }} {{ new Date(ac.createTime) | getTime }}</td>
              <td>
                <router-link :to="{name: 'ShopActivityDetail', params: {id: ac.id}}"><el-button type="text">查看</el-button></router-link>
                <el-divider direction="vertical" />
                <router-link v-if="ac.finishTime - parseInt(new Date().getTime()) > 0" :to="{name: 'ShopActivityEdit', params: {id: ac.id}}"><el-button type="text">编辑</el-button></router-link>
                <el-button v-else :disabled="true" type="text">编辑</el-button>
                <el-divider direction="vertical" />
                <el-button type="text" @click="handleDelete(ac.id)">删除</el-button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          :current-page.sync="pageNo"
          :page-size="pageSize"
          layout="prev, pager, next, sizes, jumper"
          :total="activityCount"
          :hide-on-single-page="true"
          :page-sizes="[4, 10, 20]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>
<script>
import { getList, del } from '@/api/activity';
import { mapGetters } from 'vuex';
export default {
  name: 'ActivitiesShop',
  filters: {
    formatHours: value => { // 毫秒差转'Y时'
      return parseInt(Math.abs(value) / 1000 / 60 / 60) % 24;
    },
    formatMins: value => { // 毫秒差转'X天Y时Z分'
      return parseInt(Math.abs(value) / 1000 / 60) % 60;
    },
    formatDays: value => { // 毫秒差转'X天Y时Z分'
      return parseInt(Math.abs(value) / 1000 / 60 / 60 / 24);
    }
  },
  data() {
    return {
      loading: false,
      activitySearchInfo: {
        name: '',
        type: '',
        date: ['', '']
      },
      activities: [],

      checkedAll: false,
      checkedCount: 0,
      // 分页
      pageNo: 1,
      pageSize: 4,
      activityCount: 13
    };
  },
  computed: {
    ...mapGetters(['shopInfo'])
  },
  watch: {
    checkedCount(value) {
      this.checkedAll = value === this.activities.length;
    }
  },
  mounted() {
    this.getList();
  },
  activated() {
    if (this.$route.query.reload) this.getList();
  },
  methods: {
    toSearch() {
      this.currentPage = 1;
      this.getList();
    },
    getList(
      shopId = this.shopInfo.id,
      pageNo = this.pageNo,
      pageSize = this.pageSize,
      searchName = this.activitySearchInfo.name,
      type = this.activitySearchInfo.type,
      beginTime = new Date(this.activitySearchInfo.date[0]).getTime(),
      finishTime = new Date(this.activitySearchInfo.date[1]).getTime()
    ) {
      this.loading = true;
      new Promise((resolve, reject) => {
        getList({ shopId, pageNo, pageSize, type, searchName, beginTime, finishTime }).then(res => {
          this.loading = false;
          this.activityCount = res.data.size;
          this.activities = res.data.ativity;
          resolve(res);
        }).catch(err => {
          reject(err);
        });
      });
    },
    resetSearchInfo() {
      Object.assign(this.$data.activitySearchForm, this.$options.data().activitySearchForm);
    },
    checkAll(value) {
      this.checkedCount = value ? this.activities.length : 0;
      this.activities.forEach(ac => {
        ac.selected = value;
      });
    },
    checkItem(value) {
      value ? this.checkedCount++ : this.checkedCount--;
    },
    clearAll() {
      if (this.checkedCount === 0) return;
      this.checkedCount = 0;
      this.checkedAll = false;
      this.activities.forEach(ac => {
        ac.selected = false;
      });
    },
    // 批量删除
    deleteMany() {
      if (this.checkedCount === 0) {
        this.$message({
          message: '请选择您要删除的广告',
          type: 'warning'
        });
        return false;
      }
      var selectedIdList = [];
      this.activities.filter(ac => {
        return ac.selected;
      }).map(ad => {
        selectedIdList.push(ad.id);
      });
      this.$confirm('此操作将永久删除该活动, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        new Promise((resolve, reject) => {
          del({ id: selectedIdList.join('/') }).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.pageNo = 1;
            this.clearAll();
            this.getList();
          }).catch(err => {
            reject(err);
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 删除
    handleDelete(id) {
      this.$confirm('此操作将永久删除该活动, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        new Promise((resolve, reject) => {
          del({ id }).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList();
          }).catch(err => {
            reject(err);
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.pageNo = 1;
      this.getList();
    },
    handleCurrentChange(val) {
      this.pageNo = val;
      this.getList();
    }
  }
};
</script>
<style lang="scss" scoped>
@import '@/styles/shop-activity.scss';
.ad-list-wrapper{
  min-height: calc(100vh - 285px);
}
.ad-list{
  .func{
    width: 170px;
  }
  table{
    td{
      &.create-date{
        color: $textColorBase;
        padding: 20px 5px;
      }
      &.date{
        padding: 20px 5px;
      }
    }
  }
}
</style>
